<template>
  <view class="menu-container">
    <!-- 左侧一级菜单侧边栏 -->
    <scroll-view class="sidebar" scroll-y>
      <view class="sidebar-header">
        <view class="app-logo">
          <image
            src="@/static/image/logo.png"
            mode="aspectFit"
            class="logo-image"
          ></image>
        </view>
      </view>
      <view class="sidebar-menu">
        <SidebarItem
          v-for="(menu, index) in menus"
          :key="menu.id"
          :icon="menu.icon.toLowerCase()"
          :title="menu.label"
          :is-active="currentMenuIndex === index"
          badge-type="new"
          :style="{ animationDelay: `${index * 0.05}s` }"
          class="fade-in"
          @click="selectMenu(index)"
        />
      </view>
    </scroll-view>

    <!-- 右侧二级菜单内容区 -->
    <scroll-view class="content" scroll-y>
      <view class="content-header">
        <view class="header-title-row">
          <text class="content-title">{{
            currentMenu ? currentMenu.label : ""
          }}</text>
          <text class="content-subtitle"
            >{{ currentSubMenus.length }}个功能</text
          >
        </view>
        <view class="header-actions">
          <view class="search-box">
            <up-icon name="search" size="18" color="#999"></up-icon>
            <input
              class="search-input"
              type="text"
              placeholder="搜索功能"
              v-model="searchQuery"
            />
          </view>
        </view>
      </view>

      <view v-if="filteredSubMenus.length === 0" class="empty-state">
        <up-icon name="info-circle" size="50" color="#cccccc"></up-icon>
        <text class="empty-text">{{
          searchQuery ? "没有找到匹配的功能" : "此模块暂无可用功能"
        }}</text>
      </view>

      <view v-else class="content-body">
        <MenuItem
          v-for="(subMenu, idx) in filteredSubMenus"
          :key="subMenu.id"
          :icon="subMenu.icon.toLowerCase()"
          :title="subMenu.label"
          :description="subMenu.description || '点击进入功能'"
          :icon-bg-color="getIconBgColor(idx)"
          :style="{ animationDelay: `${idx * 0.05}s` }"
          class="fade-in"
          @click="handleSubMenuClick(subMenu)"
        />
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { reactive, ref, computed, onMounted } from "vue";
import { getCurrentUserMenuList } from "@/api/menu";
import SidebarItem from "@/components/SidebarItem.vue";
import MenuItem from "@/components/MenuItem.vue";

// 菜单数据
const menus = reactive([]);

// 当前选中的菜单索引
const currentMenuIndex = ref(0);

// 搜索关键词
const searchQuery = ref("");

// 计算当前选中的菜单
const currentMenu = computed(() => {
  return menus[currentMenuIndex.value];
});

// 计算当前选中菜单的子菜单
const currentSubMenus = computed(() => {
  // 如果当前选中的菜单的子菜单中路径不为空的子菜单，否则则返回空数组
  return currentMenu.value?.children?.filter((item) => item.path) || [];
});

// 过滤后的子菜单（基于搜索）
const filteredSubMenus = computed(() => {
  if (!searchQuery.value) return currentSubMenus.value;

  return currentSubMenus.value.filter(
    (item) =>
      item.label.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      (item.description &&
        item.description
          .toLowerCase()
          .includes(searchQuery.value.toLowerCase()))
  );
});

// 为图标生成背景色
const getIconBgColor = (index) => {
  const colors = [
    "linear-gradient(135deg, #36CCCB, #188FFF)",
    "linear-gradient(135deg, #52C873, #009900)",
    "linear-gradient(135deg, #FFB545, #FF8C00)",
    "linear-gradient(135deg, #FF6B78, #E74C3C)",
    "linear-gradient(135deg, #A084DC, #645CBB)",
    "linear-gradient(135deg, #FF8FB1, #E74C3C)",
  ];

  return colors[index % colors.length];
};

// 选择菜单
const selectMenu = (index) => {
  currentMenuIndex.value = index;
  // 重置搜索
  searchQuery.value = "";
};

// 处理二级菜单点击
const handleSubMenuClick = (subMenu) => {
  if (subMenu.path) {
    // 获取最后一个/后面的所有字符串
    const path =
      "/pages/" +
      subMenu.path.split("/").pop() +
      "/" +
      subMenu.path.split("/").pop();
    console.log("点击的菜单路径：", path);
    uni.navigateTo({
      url: path,
      fail: (err) => {
        uni.showToast({
          title: "功能暂未实现",
          icon: "none",
        });
        console.error(err);
      },
    });
  }
};

// 获取菜单数据
const getMenuData = async () => {
  try {
    const res = await getCurrentUserMenuList();
    if (res.success) {
      // 只获取pid为0的一级菜单
      const menuData = res.data
        .filter(
          (item) => item.pid === 0 && item.children && item.children.length > 0
        )
        .map((menu) => {
          // 随机添加一些新功能标记用于演示
          return {
            ...menu,
            // hasNewItems: Math.random() > 0.7,
          };
        });

      menus.push(...menuData);
      // 默认选中第一个菜单
      if (menuData.length > 0) {
        selectMenu(0);
      }
    }
  } catch (error) {
    console.error("获取菜单数据失败：", error);
  }
};

// 页面加载时获取菜单数据
onMounted(() => {
  getMenuData();
});
</script>

<style lang="scss" scoped>
.menu-container {
  display: flex;
  height: 100vh;
  background-color: #f7f7f7;
}

.sidebar {
  width: 160rpx;
  height: 100%;
  background-color: #ffffff;
  box-shadow: 2rpx 0 10rpx rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  position: relative;
  z-index: 10;

  .sidebar-header {
    padding: 30rpx 0;
    display: flex;
    justify-content: center;
    align-items: center;
    border-bottom: 1rpx solid #eee;

    .app-logo {
      width: 80rpx;
      height: 80rpx;
      border-radius: 8rpx;
      overflow: hidden;
      box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.1);

      .logo-image {
        width: 100%;
        height: 100%;
      }
    }
  }

  .sidebar-menu {
    flex: 1;
    padding: 0;
  }
}

.content {
  flex: 1;
  height: 100%;
  background-color: #f7f7f7;

  .content-header {
    padding: 24rpx 24rpx 20rpx;
    background-color: #ffffff;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    display: flex;
    flex-direction: column;

    .header-title-row {
      display: flex;
      align-items: center;
      margin-bottom: 16rpx;
    }

    .content-title {
      font-size: 34rpx;
      font-weight: bold;
      color: #333333;
      margin-right: 16rpx;
    }

    .content-subtitle {
      font-size: 24rpx;
      color: #999999;
      background-color: #f0f0f0;
      padding: 4rpx 16rpx;
      border-radius: 100rpx;
      display: inline-block;
    }

    .header-actions {
      margin-left: 0;
      display: flex;
      align-items: center;

      .search-box {
        display: flex;
        align-items: center;
        background-color: #f0f0f0;
        border-radius: 100rpx;
        padding: 12rpx 24rpx;
        width: 100%;

        .search-input {
          margin-left: 12rpx;
          flex: 1;
          font-size: 24rpx;
          height: 48rpx;
          color: #333333;
          background: transparent;
        }
      }
    }
  }
}

.content-body {
  padding: 10rpx 20rpx 30rpx;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320rpx, 1fr));
  grid-gap: 20rpx;
}

.empty-state {
  height: 400rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx;

  .empty-text {
    margin-top: 24rpx;
    font-size: 28rpx;
    color: #999999;
  }
}

// 大屏幕适配
@media screen and (min-width: 768px) {
  .sidebar {
    width: 200rpx;
  }

  .content-body {
    grid-template-columns: repeat(auto-fill, minmax(400rpx, 1fr));
    padding: 20rpx 30rpx 40rpx;
  }
}
</style>
